import Taro, { Component } from '@tarojs/taro'
import PropTypes from 'prop-types'
import { View } from '@tarojs/components'
import { AtImagePicker } from 'taro-ui'

import { upload2server, convertObjectUrlToBlob, compressImage } from '../../utils'
import RowItem from '../RowItem'
import start_img from '../../assets/icon_star.png'
import './index.scss'

class UploadImg extends Component {

	static propTypes = {
		onSelect: PropTypes.func,
		star: PropTypes.bool,
		title: PropTypes.string,
		images: PropTypes.oneOfType([
			PropTypes.array,
			PropTypes.object
		])
	}

	static defaultProps = {
		stat: true,
		title: '物品照片',
		images: [],
	}

	constructor(props){
		super(props)
		this.state = {
			media: [],
			imageFiles: []
		}
	}

	componentWillMount(){
		const { images } = this.props
		if(images){
			let list = images.map(img => {
				return {url: img }
			})
			this.setState({ imageFiles: list })
		}
	}

	componentDidMount(){
		// const ele = document.getElementsByClassName('at-image-picker__choose-btn')
		// console.log('dom===', document.getElementsByClassName('at-image-picker__choose-btn'))
	}
	componentWillReceiveProps(nextProps){
		const { images } = nextProps
		if(images){
			let list = images.map(img => {
				return {url: img }
			})
			this.setState({ imageFiles: list })
		}
	}

	render(){
		const { imageFiles } = this.state
		const { star, title } = this.props
		return(
			<View className='img-content'>
				<RowItem title={title} img={star? start_img : ''} height={42} border={false} />
				<AtImagePicker
					className='upload-img-picker'
					ref='at_image_picker'
					mode='aspectFill'
					files={imageFiles}
					count={1}
					length={3}
					showAddBtn={imageFiles.length < 3}
					sizeType={['compressed']}
					onChange={this.selectImages.bind(this)}
					onFail={this.selectImageFail.bind(this)}
				></AtImagePicker>
			</View>
		)
	}

	selectImages = (files, operationType, index) =>{
		const { onSelect } = this.props
    let fileArr = files
    if(files.length > 3){

      fileArr = fileArr.splice(0, 3)
    }
    let newFiles = []
		if(operationType === 'remove'){
			const media = this.state.media.filter((md, i) => i !== index)
      this.setState({
        imageFiles: fileArr,
        media
      })
			onSelect && onSelect(media)
    }else{
			// TODO: 图片路径错误，服务端无法识别
			fileArr.forEach((val) => {
				console.log('上传图片==', val)
				if(!val.file){
					newFiles.push(val.url)
					this.setState({
						media: newFiles,
					})
					this.setState({ imageFiles: fileArr})
					onSelect && onSelect(newFiles)
				}else{
					const ftype = val.file.type.split('/')[1]
					const fname = val.url.split('/')
					const filename = fname[fname.length-1] +'.'+ftype
					Taro.showLoading({ mask: true })
					upload2server((cos, data) => {
						// console.log('cos==', cos, data)
						convertObjectUrlToBlob(val.url).then(fres => {
							compressImage(fres).then(img => {							
								cos.putObject({
									Bucket: data.bucket,
									Region: data.region,
									Key: filename,
									Body: img, // 这里传入前缀
									onTaskStart: function (info) {
										// console.log('onTaskStart', info);
									
									},
								}, (err, rs) => {
									Taro.hideLoading()
									if(!err){
										const url = `${data.domain}/${filename}`
										newFiles.push(url)
									
										this.setState({
											media: newFiles,
										})
										this.setState({ imageFiles: fileArr})
										onSelect && onSelect(newFiles)
									}
								});
							})
						})
					})
				}
			})
		}
  }
  
  selectImageFail(mes) {
		Taro.showToast({ title: '请重新上传图片', icon: 'none'})
    console.log('选择图片失败=', mes)
  }
}

export default UploadImg